<?php

namespace app\admin\controller\user;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use Symfony\Component\VarDumper\Tests\Fixture\DumbFoo;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="user")
 */
class User extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\User();

    }

    /**
     * @NodeAnotation(title="批量设置课程")
     */
    public function batchCourse()
    {
        if ($this->request->isPost()) {
            $node1 = [];
            $node2 = [];
            $topic1 = [];
            $topic2 = [];
            $post = $this->request->post();
            $userId = Db::name('user')->where(['unit' => $post['unit']])->column('id');
            $userId = array_values($userId);
            foreach ($userId as $k => $v) {
                if ($post['node1']) {
                    $value1 = [
                        'node' => $post['node1'],
                        'uid' => $v,
                        'type' => 1,
                        'table1' => 'course',
                        'table2' => 'subjects',
                        'table3'=> 'user_online_topic'
                    ];
                    $node1 = $this->userTopic($value1);
                    $topic1 = array_merge($topic1,$node1);
                }
                if ($post['node2']) {
                    $value2 = [
                        'node' => $post['node2'],
                        'uid' => $v,
                        'type' => 2,
                        'table1' => 'offline_course',
                        'table2' => 'offline_subjects',
                        'table3'=> 'user_offline_topic'
                    ];
                    $node2 = $this->userTopic($value2);
                    $topic2 = array_merge($topic2,$node2);
                }
            }
            $topic1 = array_values($topic1);
            $topic2 = array_values($topic2);
            try {
                $save1 = Db::name('user_online_topic')->insertAll($topic1);
                $save2 = Db::name('user_offline_topic')->insertAll($topic2);
            } catch (\Exception $e) {
                return ['code' => 0, 'message' => '批量设置失败'];
            }
            if ($save1 || $save2) {
                return ['code' => 1, 'message' => '批量设置成功'];
            }
            return ['code' => 0, 'message' => '批量设置失败'];
        }
        $getUnit = Db::name('user')->field('unit')->group('unit')->select()->toArray();
        $this->assign('getUnit', $getUnit);
        return $this->fetch();
    }


    protected function userTopic($data)
    {
        $list = [];
        if($data['node']){
            $i = 0;
            $ids = explode(',', $data['node']);
            foreach ($ids as $k => $v) {
                list($sid, $cids) = explode('-', $v);
                //获取科目名称
                $sidTitle = Db::name($data['table2'])->where('id', $sid)->value('title');
                $cids = explode('|',$cids);
                foreach ($cids as $k1 => $v1) {
                    $re = explode('.', $v1);
                    //获取课程名称
                    if($data['type'] == 2){
                        $filed = 'title,video_images,rand_num,content,learn_time,score';
                    }else{
                        $filed = 'title,video_images,rand_num,content,score';
                    }
                    $cidTitle = Db::name($data['table1'])->where('id', $re[1])->field($filed)->find();
                    $list[$i] = [
                        'uid' => $data['uid'],
                        'sid' => $sid,
                        'sid_title' => $sidTitle,
                        'cid' => $re[1],
                        'cid_title' => $cidTitle['title'],
                        'video_images' => $cidTitle['video_images'],
                        'rand_num' => $cidTitle['rand_num'],
                        'content' => $cidTitle['content'],
                        'score' => $cidTitle['score']
                    ];
                    if($data['type'] == 2){
                        $list[$i]['learn_time'] = $cidTitle['learn_time'];
                    }
                    $i++;
                }
            }
        }
        if($data['type'] == 2){
            $filed1 = 'uid,sid,sid_title,cid,cid_title,video_images,rand_num,content,learn_time,score';
        }else{
            $filed1 = 'uid,sid,sid_title,cid,cid_title,video_images,rand_num,content,score';
        }
        //已设置的课程
        $userTopic = Db::name($data['table3'])->field($filed1)->where(['uid' => $data['uid']])->select()->toArray();
        if ($userTopic) {
            //删除未选中的
            $res = array_filter($userTopic, function($v) use ($list) { return ! in_array($v, $list);});
            if($res){
                foreach ($res as $val){
                    Db::name('table3')->where($val)->delete();
                }
            }
            //求差集 去掉已经设置过的
            $list = array_filter($list, function($v) use ($userTopic) { return ! in_array($v, $userTopic);});
        }
        return $list;
    }


    /**
     * @NodeAnotation(title="获取批量课程数据")
     */
    public function batchCourseData()
    {
        return $this->getBatchCourseData(2);
    }

    protected function getBatchCourseData($type, $userOnlineTopic = [],$userOfflineTopic = [])
    {
        $course = Db::name('course')->field('id,sid,title,score')->select();
        $subjects = Db::name('subjects')->field('id,title')->select();
        foreach ($subjects as $k => $v) {
            $data[$k]['id'] = $v['id'];
            $data[$k]['title'] = $v['title'];
            $data[$k]['checked'] = false;
            $data[$k]['field'] = 'node1';
            $data[$k]['spread'] = true;
            $data[$k]['children'] = [];
            foreach ($course as $key => $val) {
                if ($v['id'] == $val['sid']) {
                    $data[$k]['children'][$key]['id'] = $v['id'].'.'.$val['id'];
                    $data[$k]['children'][$key]['title'] = $val['title']."(".$val['score']."分)";
                    $data[$k]['children'][$key]['field'] = 'node2';
                    $data[$k]['children'][$key]['spread'] = true;
                    $data[$k]['children'][$key]['checked'] = ($type == 2) ? $this->getUserTopic($userOnlineTopic, $v['id'], $val['id']) : false;
                }
                $data[$k]['children'] = array_values($data[$k]['children']);
            }
        }
        $course = Db::name('offline_course')->field('id,sid,title,score')->select();
        $subjects = Db::name('offline_subjects')->field('id,title')->select();
        foreach ($subjects as $k => $v) {
            $list[$k]['id'] = $v['id'];
            $list[$k]['title'] = $v['title'];
            $list[$k]['checked'] = false;
            $list[$k]['field'] = 'node3';
            $list[$k]['spread'] = true;
            $list[$k]['children'] = [];
            foreach ($course as $key => $val) {
                if ($v['id'] == $val['sid']) {
                    $list[$k]['children'][$key]['id'] = $v['id'].'.'.$val['id'];
                    $list[$k]['children'][$key]['title'] = $val['title']."(".$val['score']."分)";
                    $list[$k]['children'][$key]['field'] = 'node4';
                    $list[$k]['children'][$key]['spread'] = true;
                    $list[$k]['children'][$key]['checked'] = ($type == 2) ? $this->getUserTopic($userOfflineTopic, $v['id'], $val['id']) : false;
                }
            }
            $list[$k]['children'] = array_values($list[$k]['children']);
        }

        return ['online' => $data, 'offline' => $list];
    }

    //
    protected function getUserTopic($userTopic, $sid, $cid)
    {
        $i = 0;
        foreach ($userTopic as $k => $v) {
            if ($v == ['sid' => $sid, 'cid' => $cid]) {
                $i = 1;
                break;
            }
        }
        return $i == 1 ? true : false;
    }

    /**
     * @NodeAnotation(title="设置课程数据")
     */
    public function settopic($id)
    {
        //已设置的课程
        if ($this->request->isAjax()) {
            $userOnlineTopic = Db::name('user_online_topic')->field('sid,cid')->where(['uid' => $id])->select()->toArray();
            $userOfflineTopic = Db::name('user_offline_topic')->field('sid,cid')->where(['uid' => $id])->select()->toArray();
            return $this->getBatchCourseData(2, $userOnlineTopic,$userOfflineTopic);
        }
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function setTopicSave()
    {
        $node1 = [];
        $node2 = [];
        $post = $this->request->post();
        $value1 = [
            'node' => $post['node1']??[],
            'uid' => $post['id'],
            'type' => 1,
            'table1' => 'course',
            'table2' => 'subjects',
            'table3'=> 'user_online_topic'
        ];
        $node1 = $this->userTopic($value1);
        $node1 = array_values($node1);

        $value2 = [
            'node' => $post['node2']??[],
            'uid' => $post['id'],
            'type' => 2,
            'table1' => 'offline_course',
            'table2' => 'offline_subjects',
            'table3'=> 'user_offline_topic'
        ];
        $node2 = $this->userTopic($value2);
        $node2 = array_values($node2);
        if (!$node1 && !$node2) {
            return ['code' => 1, 'message' => '已设置该系列科目'];
        }
        try {
            $save1 = Db::name('user_online_topic')->where(['id' => $post['id']])->insertAll($node1);
            $save2 = Db::name('user_offline_topic')->where(['id' => $post['id']])->insertAll($node2);
        } catch (\Exception $e) {
            return ['code' => 0, 'message' => '设置失败'];
        }
        if ($save1 !== false || $save2 !== false) {
            return ['code' => 1, 'message' => '设置成功'];
        }
        return ['code' => 0, 'message' => '设置失败'];
    }
}